package com.sjh.net.interceptor

import com.sjh.net.HttpInfoEntity

import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
import java.util.concurrent.TimeUnit

import okhttp3.Interceptor
import okhttp3.Protocol
import okhttp3.Response
import okio.Buffer

/**
 * Http请求信息拦截器，在Retrofit build的过程中添加
 * Created by linxiao on 2016/12/4.
 */
class HttpInfoCatchInterceptor : BaseInterceptor() {


    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        val entity = HttpInfoEntity()

        val requestBody = request.body()

        val connection = chain.connection()

        val protocol = if (connection != null) connection.protocol() else Protocol.HTTP_1_1
        entity.protocol = protocol.toString()
        entity.method = request.method()
        entity.url = request.url().toString()
        entity.requestHeaders = request.headers().apply { this }

        if (requestBody != null) {
            entity.requestContentType = requestBody.contentType()!!.toString()
            entity.requestContentLength = requestBody.contentLength()
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset: Charset? =
                UTF8
            val contentType = requestBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(UTF8)
            }
            entity.requestBody = buffer.readString(charset!!)
        }
        //-----request prepare----
        val startNs = System.nanoTime()
        val response: Response
        response = chain.proceed(request)
        //-----request done--------

        entity.tookMills = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)

        val responseBody = response.body()
        entity.responseHeaders = response.headers()
        entity.responseCode = response.code()
        entity.responseMessage = response.message()
        entity.responseContentLength = responseBody!!.contentLength()
        if (response.body() != null) {
            val source = responseBody.source()
            source.request(java.lang.Long.MAX_VALUE) // Buffer the entire requestBody.
            val buffer = source.buffer()
            var charset: Charset? =
                UTF8
            val contentType = responseBody.contentType()
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8)
                } catch (e: UnsupportedCharsetException) {
                    entity.responseBody = "unreadable, charset error"
                }

            }
            if (isPlaintext(buffer) && responseBody.contentLength() != 0L) {
                entity.responseBody = buffer.clone().readString(charset!!)
            } else {
                entity.responseBody = "unreadable, not text"
            }
        }
        //打印语句

        //如果请求内容大于1024的长度，则默认认为是上传文件
        entity.logOut()
//        if(entity.requestBody?.length?:0 > 1024){ 判断有问题，暂时直接打印请求体
//            entity.logOutNoRequestBody()
//        }else{
//            entity.logOut()
//        }

        return response
    }

    companion object {

        private val UTF8 = Charset.forName("UTF-8")
    }
}
